<?php

/*
	Class: Commerce_CatalogController

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>
*/
class Commerce_CatalogController extends Commerce_Controller {

	/*
		Function: init
	*/
	function init() {
		parent::init();
	}
	
	/*
		Function: mysteryAction
	*/
	function mysteryAction() {
		$request = new Cts_Request($this->getRequest());
		$catalog_table = new CommerceMagentoCatalog();

		$product_id = $catalog_table->getProductIdByUrlKey($request->product_key, $this->locale_code);

		if (!is_null($product_id)) {
			## This is a product
			$this->_forward('product', null, null, array(
				'action'=>'product',
				'id'=>$product_id,
			));
			return;
		} else {
			## Maybe it's a category									## Product key is really the sub-category
			$category_id = $catalog_table->getCategoryIdByUrlKey($request->product_key, $this->locale_code);
			if (!is_null($category_id)) {
				## This is a category
				$this->_forward('category', null, null, array(
					'action' => 'category',
					'id' => $category_id,
					'category_key' => $request->product_key,
					'product_key' => NULL
				));
				return;
			} else {
				$this->_redirect("/default/auth/missing");
			}
		}
	}

	/*
		Function: indexAction
	*/
	function indexAction() {

		// NOTE - this action is not used, it's only here for development purposes

		$request = new Cts_Request($this->getRequest());
		$catalog_table = new CommerceMagentoCatalog();
		$this->view->category = $catalog_table->getCategory(Cts_Registry::get("magento_root_category_id", "commerce"));
		$this->view->subcategories = $catalog_table->getCategoryTree(Cts_Registry::get("magento_root_category_id", "commerce"));
	}

	/*
		Function: activityAction
	*/
	function activityAction() {
		$request = new Cts_Request($this->getRequest());
		$catalog_table = new CommerceMagentoCatalog();
		$blog_table = new BlogPosts();
		$blogcats_table = new BlogCategories();
		$users_table = new Users();

		if ($request->has('id')) {
			$category_id = $request->id;
		} elseif ($request->has('activity_key')) {
			$category_id = $catalog_table->getCategoryIdByUrlKey($request->activity_key, $this->locale_code);
		} else {
			$this->_redirect("/default/auth/missing");
		}

		$category = $catalog_table->getCategory($category_id, $this->locale_code);
		$this->view->category = $category;

		if (array_key_exists('blackdiamond_swiftcollective_related_categories', $category) && $category['blackdiamond_swiftcollective_related_categories'] != '') {
			$related = explode(",", $category['blackdiamond_swiftcollective_related_categories']);
			$rel_cats = array();
			foreach ($related as $catid) {
				$tmp_cat = $catalog_table->getCategory($catid, $this->locale_code);
				$rel_cats[] = array(
					'url' => "/shop/".$category['url_key']."/".$tmp_cat['url_key'],
					'name' => $tmp_cat['name'],
					'url_key' => $tmp_cat['url_key'],
					'thumbnail_url' => $tmp_cat['blackdiamond_swiftcollective_cat_thumb'],
				);
			}
			$this->view->rel_cats = $rel_cats;
		}
		$alp_tag = Cts_Registry::get('alp_tag_prefix','commerce').strtolower($category['url_key']);
		
		$tmp_journal_posts = $blog_table->fetchAllByTags(array($alp_tag), false, 3);
		$excluded_ids = array();
		if(count($tmp_journal_posts) > 0){
			$tmp_journal_posts = $tmp_journal_posts->toArray();	
			
			foreach($tmp_journal_posts as $t_post){
				$excluded_ids[] = $t_post['id'];
			}		
		} else {
			$tmp_journal_posts = array();
		}	
		
		if (count($tmp_journal_posts) < 3) {
			$total = 3 - count($tmp_journal_posts);
			$alp_tag = strtolower($category['url_key']);			
			$additional_journal_posts = $blog_table->fetchAllByTags(array($alp_tag), false, $total,null,"any",$excluded_ids);
			if(count($additional_journal_posts) > 0){
				$additional_journal_posts = $additional_journal_posts->toArray();
				foreach($additional_journal_posts as $add_post){
					$tmp_journal_posts[] = $add_post;
				}
			}			
		}	
		// FEATURE IMAGE
		$feature_photo = array();
		$feature_photo['athlete_name'] = $category['blackdiamond_swiftcollective_cat_bg_athlete'];
		$feature_photo['location'] = $category['blackdiamond_swiftcollective_cat_bg_location'];
		$feature_photo['photographer_name'] = $category['blackdiamond_swiftcollective_cat_bg_photographer'];
		$feature_photo['featured_image_url'] = $category['blackdiamond_swiftcollective_cat_bg_full'];
		$feature_photo['featured_cropped_image_url'] = $category['blackdiamond_swiftcollective_cat_bg_cropped'];
		// blackdiamond_swiftcollective_cat_bg_caption
		$this->view->feature_photo = $feature_photo;
			
		if (count($tmp_journal_posts) > 0) {
			
			$journal_posts = array();
			foreach ($tmp_journal_posts as $post) {
				$cats = $blogcats_table->getParsedSlugsByPostId($post['id'], true);
				$journal_posts[] = array(
					'cats' => $cats,
					'title' => $post['title'],
					'body' => strip_tags($post['body']),
					'publish_on' => $post['publish_on'],
					'slug' => $post['slug'],
					'author_fullname' => $users_table->getFullNameByUsername($post['author_username']),
					'thumbnail_url' => $blog_table->getThumbnailUrl($post['id'], 163),
				);
			}
		}
		$this->view->journal_posts = $journal_posts;

		$tmp_subcategories = $catalog_table->getCategoryTree($category_id, $this->locale_code);
		$subcategories = array();
		foreach ($tmp_subcategories as $tmp_cat) {
			$cat_info = $catalog_table->getCategory($tmp_cat['category_id']);
			$cat = array();
			$cat['id'] = $cat_info['category_id'];
			$cat['name'] = $cat_info['name'];
			$cat['url_key'] = $cat_info['url_key'];
			$cat['thumb'] = $cat_info['blackdiamond_swiftcollective_cat_thumb'];
			$subcategories[] = $cat;
		}
		$this->view->subcategories = $subcategories;
		$blank_tile_count = 4 - (count($subcategories) % 4);
		if ($blank_tile_count == 4) {
			$blank_tile_count = 0;
		}
		$this->view->blank_tile_count = $blank_tile_count;

	}

	/*
		Function: categoryAction
	*/
	function categoryAction() {
		
		memory_profiler("start Commerce Category Action");
		
		$request = new Cts_Request($this->getRequest());
		$catalog_table = new CommerceMagentoCatalog();
		$blogcats_table = new BlogCategories();
		
		$attributes = array('blackdiamond_swiftcollective_cat_allow_comparisons');
		
		// USE THE PROVIDED CATEGORY ID
		if ($request->has('id')) {
			$category_id = $request->id;
			$category = $catalog_table->getCategory($category_id, $attributes);
		
		// SEARCH FOR THE CATEGORY BY KEY (with supoprt for multiple keys)
		} elseif ($request->has('activity_key') && $request->has('category_key')) {
			$activity_id = $catalog_table->getCategoryIdByUrlKey($request->activity_key, $this->locale_code);
			$category_ids = $catalog_table->getCategoryIdByUrlKey($request->category_key, $this->locale_code, true);
			
			if( count($category_ids)>1 ){
				foreach( $category_ids as $category_id ){
					$category = $catalog_table->getCategory($category_id);
					if( $category['parent_id'] == $activity_id ){
						break;
					}
				}
			} elseif( count($category_ids)==1 ){
				$category_id = $category_ids[0];
				$category = $catalog_table->getCategory($category_id);
			} else {
				$this->_redirect("/default/auth/missing");
			}
		
		// ERROR OUT
		} else {
			$this->_redirect("/default/auth/missing");
		}
		
		memory_profiler("Commerce Category Action Tick 1");
		
		// CATEGORY
		$this->view->category = $category;
		
		// BREADCRUMB
		$breadcrumb = $this->getBreadcrumb($category);
		$this->view->breadcrumb = $breadcrumb;
		$this->view->breadcrumb_separator = Cts_Registry::get('category_separator');
		
		// ACTIVITY
		$this->view->activity = $breadcrumb[0];
		$activity_name = $breadcrumb[0]['name'];
		
		// SPARE PARTS
		if( isset($category['blackdiamond_swiftcollective_cat_is_spareparts']) && $category['blackdiamond_swiftcollective_cat_is_spareparts']=='1' ){
			$this->view->is_spare_parts = true;
		} else {
			$this->view->is_spare_parts = false;
		}
		
		// KITS
		if( isset($category['blackdiamond_swiftcollective_cat_is_kit']) && $category['blackdiamond_swiftcollective_cat_is_kit']=='1' ){
			$is_kit = true;
			$this->view->is_kit = true;
		} else {
			$is_kit = false;
			$this->view->is_kit = false;
		}
		
		memory_profiler("Commerce Category Action Tick 2");
		
		// RELATED GEAR
		if ( $is_kit && array_key_exists('blackdiamond_swiftcollective_related_categories', $category) && $category['blackdiamond_swiftcollective_related_categories'] != '') {
			$related = explode(",", $category['blackdiamond_swiftcollective_related_categories']);
			$rel_cats = array();
			foreach ($related as $catid) {
				$tmp_cat = $catalog_table->getCategory($catid, $this->locale_code);
				$rel_cats[] = array(
					'url' => "/shop/".$category['url_key']."/".$tmp_cat['url_key'],
					'name' => $tmp_cat['name'],
					'url_key' => $tmp_cat['url_key'],
					'thumbnail_url' => $tmp_cat['blackdiamond_swiftcollective_cat_thumb'],
				);
			}
			$this->view->rel_cats = $rel_cats;
		}

		// TOGGLE HTML HEADER / FLASH HEADER
		$has_povs = 0;
		if (unserialize($category['blackdiamond_swiftcollective_media_active']) !== false) {
			$media_active = unserialize($category['blackdiamond_swiftcollective_media_active']);
			if (is_array($media_active) && in_array(true, $media_active)) {
				$has_povs = 1;
			} else {
				$has_povs = 0;
			}
		}
		$this->view->has_povs = $has_povs;

		// ALLOW COMPARISONS ?
		if (isset($category['blackdiamond_swiftcollective_cat_allow_comparisons']) && $category['blackdiamond_swiftcollective_cat_allow_comparisons'] == 1) {
			$this->view->allow_comparisons = true;
		} else {
			$this->view->allow_comparisons = false;
		}

		// FEATURE IMAGE
		$feature_photo = array();
		$feature_photo['athlete_name'] = $category['blackdiamond_swiftcollective_cat_bg_athlete'];
		$feature_photo['location'] = $category['blackdiamond_swiftcollective_cat_bg_location'];
		$feature_photo['photographer_name'] = $category['blackdiamond_swiftcollective_cat_bg_photographer'];
		$feature_photo['featured_image_url'] = $category['blackdiamond_swiftcollective_cat_bg_full'];
		$feature_photo['featured_cropped_image_url'] = $category['blackdiamond_swiftcollective_cat_bg_cropped'];
		// blackdiamond_swiftcollective_cat_bg_caption
		$this->view->feature_photo = $feature_photo;

		// SUBMITTED FILTERS
		$active_filters = array();
		$active_filters['category_ids'] = $category_id;
		$active_filters['__no_children'] = true;
		foreach ($request as $key => $value) {
			if (stripos($key, "uifilter_") === 0) {
				$active_filters[str_replace("uifilter_", "", $key)] = array($value);
			}
		}
		
		// GET ONLY ENABLED PRODUCTS
		$active_filters['status'] = array('like'=>'1');

		// SUBMITTED SORTING INFO
		$sort = array();
		$sort_allowed_attributes = array('price','name','position');
		$sort_allowed_directions = array('asc','desc');
		
		if ($request->has('sortby') && in_array($request->sortby,$sort_allowed_attributes)) {
			$sort['attribute'] = $request->sortby;
		} else {
			// $sort['attribute'] = "position";
			$sort['attribute'] = "price";
		}
		if ($request->has('sortdir') && in_array($request->sortdir,$sort_allowed_directions)) {
			$sort['direction'] = $request->sortdir;
		} else {
			$sort['direction'] = "desc";
		}
		
		end($breadcrumb);
		$base_sort_url = current($breadcrumb);
		$base_sort_url = '/shop/'.$base_sort_url['crumb_url'];
		$url_filter = new Cts_Url_Filter();
		$base_sort_url = $url_filter->filter($base_sort_url, array('locale_code' => $this->locale_code));
		reset($breadcrumb);
		
		$sort_options = array(
			($base_sort_url.'sortby/position/sortdir/desc/') => $this->_T('Default'),
			($base_sort_url.'sortby/name/sortdir/asc/') => $this->_T('Name: A to Z'),
			($base_sort_url.'sortby/name/sortdir/desc/') => $this->_T('Name: Z to A'),
			($base_sort_url.'sortby/price/sortdir/desc/') => $this->_T('Price: High to Low'),
			($base_sort_url.'sortby/price/sortdir/asc/') => $this->_T('Price: Low to High'),
		);
		
		$sort_current = $base_sort_url.'sortby/'.$sort['attribute'].'/sortdir/'.$sort['direction'].'/';
		
		$this->view->sort_options = $sort_options;
		$this->view->sort_current = $sort_current;
		
		memory_profiler("Commerce Category Action Tick 3");
		
		$smarty_prices = array();
		
		// PRODUCTS
		$attributes = array('status', 'name', 'price', 'special_price', 'final_price', 'description', 'short_description', 'bd_media', 'bd_filter_category', 'url_key', 'bd_is_for_sale');
		$tmp_products = $catalog_table->getProducts($active_filters, $this->locale_code, $attributes, $sort);		
		$products = array();
		foreach ($tmp_products as $tmp_product) {
			
			if($tmp_product['status']!=='1'){
				continue;
			}
			
			if( $this->view->is_spare_parts==true && isset($tmp_product['bd_is_for_sale']) && $tmp_product['bd_is_for_sale']!=='1'){
				continue;
			}
			
			// This will remove any product specific stock data, and return every product to config settings
			// $catalog_table->setStockDefault( $tmp_product['product_id'] );
			
			$product = array();
			$product['product_id'] = $tmp_product['product_id'];
			$product['url_key'] = $tmp_product['url_key'];
			$product['name'] = $tmp_product['name'];
			$product['price'] = $tmp_product['price'];
			$product['description'] = $tmp_product['description'];
			$product['short_description'] = $tmp_product['short_description'];
			if( isset($tmp_product['bd_media']) ){
				$product['thumbnail'] = Commerce_Common::getThumbFromSerializedMedia($tmp_product['bd_media']);
			} else {
				$product['thumbnail'] = false;
			}
			
			if( array_key_exists('bd_is_for_sale', $tmp_product) && $tmp_product['bd_is_for_sale']==='0' ){
				$product['for_sale'] = 'no';
			} else {
				$product['for_sale'] = 'yes';
			}

			$prices = array('price'=>array(),'special_price'=>array(),'final_price'=>array());
			
			if( $tmp_product['type']=='configurable' ){
				$children = $catalog_table->getChildrenProducts($product['product_id'], $this->locale_code, array('special_price'));
				if( is_array($children) && !empty($children) ){
					foreach( $children as $child ){
						// This will remove any product specific stock data, and return every product to config settings
						// $catalog_table->setStockDefault( $child['product_id'] );
						
						$prices['price'][] = @$child['price'];
						$prices['special_price'][] = @$child['price'];
						$prices['final_price'][] = @$child['final_price'];
						if(array_key_exists('special_price', $child) && !empty($child['special_price'])){
							$prices['special_price'][] = $child['special_price'];
						}
					}
				}
			} else {
				$prices['price'][] = @$tmp_product['price'];
				$prices['special_price'][] = @$tmp_product['price'];
				$prices['final_price'][] = @$tmp_product['final_price'];
				if(array_key_exists('special_price', $tmp_product) && !empty($tmp_product['special_price'])){
					$prices['special_price'][] = $tmp_product['special_price'];
				}
			}
			
			$smarty_prices[ $product['product_id'] ] = Commerce_Common::getTemplatePrices( $prices );
			
			$products[] = $product;
		}
		
		$this->view->prod_count = count($products);
		$this->view->prod_count_label = Cts_Common::pluralOrSingular(count($products), "product", "products");
		$this->view->products = $products;
		$this->view->prices = $smarty_prices;
		
		memory_profiler("Commerce Category Action Tick 4");

		// JOURNAL POSTS
		$blog_table = new BlogPosts();
		$users_table = new Users();		
		$cts_filter = new Cts_FilterTags();		
		
		if( $is_kit ){
			$pcp_tag = strtolower($activity_name);					
			$tmp_journal_posts = $blog_table->fetchAllByTags(array($pcp_tag), false, 3);	
			if(count($tmp_journal_posts) > 0){
				$tmp_journal_posts = $tmp_journal_posts->toArray();
			}		
		} else {
			$pcp_tag = Cts_Registry::get('pcp_tag_prefix','commerce').$cts_filter->filter($category['url_key']);					
			$tmp_journal_posts = $blog_table->fetchAllByTags(array($pcp_tag), false, 3);
			if(count($tmp_journal_posts) == 0 ){
				$pcp_tag = $cts_filter->filter($category['url_key']);
				$tmp_journal_posts = $blog_table->fetchAllByTags(array($pcp_tag), false, 3);
				
			}
			$excluded_ids = array();
			if(count($tmp_journal_posts) > 0){
				$tmp_journal_posts = $tmp_journal_posts->toArray();
				
				foreach($tmp_journal_posts as $t_post){
					$excluded_ids[] = $t_post['id'];
				}
			} else {
				$tmp_journal_posts = array();
			}
			
			if (count($tmp_journal_posts) < 3) {
				$total = 3 - count($tmp_journal_posts);
				$pcp_tag = strtolower($activity_name);	
				$additional_journal_posts = $blog_table->fetchAllByTags(array($pcp_tag), false, $total,null,"any",$excluded_ids);
				if(count($additional_journal_posts) > 0){
					foreach($additional_journal_posts as $add_post){
						$tmp_journal_posts[] = $add_post->toArray();
					}
				}
			}			
			
		}		

		if (!empty($tmp_journal_posts)) {
			
			$journal_posts = array();
			foreach ($tmp_journal_posts as $post) {
				$cats = $blogcats_table->getParsedSlugsByPostId($post['id'], true);
				$journal_posts[] = array(
					'cats' => $cats,
					'title' => $post['title'],
					'body' => strip_tags($post['body']),
					'publish_on' => $post['publish_on'],
					'slug' => $post['slug'],
					'author_fullname' => $users_table->getFullNameByUsername($post['author_username']),
					'thumbnail_url' => $blog_table->getThumbnailUrl($post['id'], 163),
				);
			}
		}
		$this->view->journal_posts = $journal_posts;
		
		memory_profiler("Commerce Category Action Tick 5");

		// FILTER OPTIONS
		$tmp_filters = array();
		$tmp_filters = $catalog_table->getCategoryFilters($category_id);
		$filters = array();

		// determine if a filter checkbox should be checked
		foreach ($tmp_filters as $key => $tmp_filter) {
			$filter = array();
			$filter_key = "uifilter_".$key;
			$filter['name'] = $tmp_filter['name'];
			$filter['options'] = array();
			foreach ($tmp_filter['options'] as $tmp_option) {
				$option = array();
				$option['value'] = $tmp_option['value'];
				$option['label'] = $tmp_option['label'];
				$option['checkbox_name'] = $filter_key;
				$filter['options'][$tmp_option['value']] = $option;
			}
			if (isset($request->$filter_key)) {
				$choice_array = $request->$filter_key;
				if (isset($choice_array) && count($choice_array) > 0) {
					foreach ($choice_array as $choice) {
						foreach ($filter['options'] as $key => $option) {
							if ($key == $choice) {
								$filter['options'][$option['value']]['checked'] = true;
							}
						}
					}
				}
			}
			$filters[] = $filter;
		}
		$this->view->filters = $filters;
		
		memory_profiler("end Commerce Category Action");
	}

	/*
		Function: productAction
	*/
	function productAction() {
		memory_profiler("start pdp");

		$request = new Cts_Request($this->getRequest());
		$catalog_table = new CommerceMagentoCatalog();
		if ($request->has('id')) {
			$product_id = $request->id;
		} elseif ($request->has('product_key')) {
			$product_key = $request->product_key;
			$product_id = $catalog_table->getProductIdByUrlKey($product_key, $this->locale_code);
		} else {
			Cts_Log::report("404 Redirect :: Could not find a product with an ID of `{$request->id}` or a URL Key of `{$request->product_key}`", NULL, Zend_Log::INFO);
			$this->_redirect("/default/auth/missing");
		}
		
		$product = $catalog_table->getProduct($product_id, $this->locale_code);
		
		if ($request->has('success')) {
			$this->view->product_added = $request->success;
		}
		
		if( $product['bd_is_for_sale']==='0' ){
			$this->view->for_sale = 'no';
		} else {
			$this->view->for_sale = 'yes';
		}
		
		## Check to see if this is a child product
		if ($product['type'] == 'simple') {
			$parents = $catalog_table->getParentIds($product_id, $this->locale_code);
			if (!empty($parents)) {
				// change the product to the parent product
				$product = $catalog_table->getProduct($parents[0], $this->locale_code);
			}
		}

		// ONLY ACTIVE PRODUCTS
		if (isset($product['status']) && $product['status'] != '1') {
			Cts_Log::report("404 Redirect :: Trying to access disabled product: {$product['name']}", NULL, Zend_Log::INFO);
			$this->_redirect('/default/auth/missing/');
		}

		if (stripos($this->getRequest()->getRequestUri(), '/web-specials/') !== false) {
			$category = array(
				'url_key' => 'web-specials',
				'name' => 'Web Specials',
			);
			$feature_photo = Blackdiamond_Common::getBgImage(Cts_Registry::get('web_specials_pageparts_page_id'));
		} elseif (count($product['categories']) >= 1) {
			$category = $catalog_table->getCategory($product['categories'][0]);
			$activity = $catalog_table->getCategory($category['parent_id']);
			$this->view->activity = $activity;
			$feature_photo = array();
			$feature_photo['athlete_name'] = $category['blackdiamond_swiftcollective_cat_bg_athlete'];
			$feature_photo['location'] = $category['blackdiamond_swiftcollective_cat_bg_location'];
			$feature_photo['photographer_name'] = $category['blackdiamond_swiftcollective_cat_bg_photographer'];
			$feature_photo['featured_image_url'] = $category['blackdiamond_swiftcollective_cat_bg_full'];
			$feature_photo['featured_cropped_image_url'] = $category['blackdiamond_swiftcollective_cat_bg_cropped'];
		}
		$this->view->category = $category;
		$this->view->feature_photo = $feature_photo;

		// MEDIA
		if( isset($product['bd_media']) && !empty($product['bd_media']) ){
			$this->view->media = @unserialize($product['bd_media']);
		}

		// AWARDS
		if( isset($product['bd_awards']) && !empty($product['bd_awards']) ){
			$product['awards'] = @unserialize($product['bd_awards']);
		}

		// FEATURES
		if( isset($product['bd_features']) && !empty($product['bd_features']) ){
			$product['features'] = @unserialize($product['bd_features']);
		}

		list($groups, $attribs, $details) = Commerce_Common::getProductAttributeDetails($product_id, $this->locale_code);

		## Create a simplified options array
		foreach ($attribs as $attrib_code => $attrib) {
			if (isset($attrib['options']) && is_array($attrib['options'])) {
				foreach ($attrib['options'] as $option) {
					$attribs[$attrib_code]['options_smarty'][ $option['value'] ] = $option['label'];
				}
			}
		}

		$product['tech_specs'] = array();
		$product['configurables'] = array();
		
		$prices = array('price'=>array(),'special_price'=>array(),'final_price'=>array());
		$prices_by_id = array($product['product_id']=>$product['final_price']);

		## Add the simple product price to the price array
		if ($details['type'] != 'configurable') {
			$prices['price'][] = @$product['price'];
			$prices['special_price'][] = @$product['price'];
			$prices['final_price'][] = @$product['final_price'];
			if(array_key_exists('special_price', $product) && !empty($product['special_price'])){
				$prices['special_price'][] = $product['special_price'];
			}
		}

		foreach ($groups as $group) {
			// TECH SPECS
			if ($group['attribute_group_name'] == Cts_Registry::get('magento_attribute_group_name_tech_specs', 'commerce')) {
				foreach ($group['attributes'] as $attrib) {
					if (array_key_exists($attrib['code'], $product) && !empty($product[$attrib['code']])) {
						$tech_spec = array();
						$tech_spec['attribute_code'] = $attrib['code'];
						$tech_spec['attribute_id'] = $attrib['id'];
						$tech_spec['label'] = $attrib['label'];
						$tech_spec['value'] = $product[$attrib['code']];
						$product['tech_specs'][] = $tech_spec;
					}
				}
				
			// CONFIGURABLE ATTRIBUTES
			} elseif ($group['attribute_group_name'] == Cts_Registry::get('magento_attribute_group_name_configurable', 'commerce')) {
				if ($details['type'] == 'configurable') {
					## Get the correct configurable attributes and their labels
					$attribute_labels = array();
					foreach ( $group['attributes'] as $a) {
						$b = &$attribs[$a['code']];
						if ($b['scope'] == 'global' && in_array('simple', $b['apply_to']) && ($b['type'] == 'select' || $b['type'] == 'multiselect')) {
							$attribute_labels[$b['code']] = $b['label'];
						}
					}

					## Sort the attributes so that bd_color is always first
					uksort($attribute_labels, array($this, 'sort_by_attribute_code'));
					$attribute_codes = array_keys($attribute_labels);

					## To get color swatches or not
					if (in_array('bd_color', $attribute_codes)) {
						$get_attributes = array_merge($attribute_codes, array('bd_color_swatch_one', 'bd_color_swatch_two', 'price', 'special_price'));
					} else {
						$get_attributes = array_merge($attribute_codes, array('price', 'special_price'));
					}
					
					$children = $catalog_table->getChildrenProducts( $details['product_id'], $this->locale_code, $get_attributes );

					## Get all of the attribute configurations
					$combos = array();
					$combos_verbose = array();
					$attributes = array();
					$color_swatches = array();
					foreach ($children as $child_key => $child_info) {
						$child = $child_info['product_id'];
						
						## If this child is disabled (should never happen) remove it from the array
						if (isset($child_info['status']) && $child_info['status'] != '1') {
							unset($children[$child_key]);
						}
						
						## Add the child price to the prices array
						$prices['price'][] = @$child_info['price'];
						$prices['special_price'][] = @$child_info['price'];
						$prices['final_price'][] = @$child_info['final_price'];
						if(array_key_exists('special_price', $child_info) && !empty($child_info['special_price'])){
							$prices['special_price'][] = $child_info['special_price'];
						}
						
						## Add the child price to the prices by id array
						$prices_by_id[$child] = $child_info['final_price'];

						$combos[ $child ] = array();
						foreach ($get_attributes as $attribute_code) {
							## Get the color swatches while we're in here
							if ($attribute_code == 'bd_color_swatch_one' || $attribute_code == 'bd_color_swatch_two') {
								if( array_key_exists($attribute_code, $child_info) ){
									$color = $child_info[$attribute_code];
	
									if (!array_key_exists($child_info['bd_color'], $color_swatches)) {
										$color_swatches[$child_info['bd_color']] = array('one' => '', 'two' => '');
									}
	
									if (!in_array($color, $color_swatches[$child_info['bd_color']]) && !empty($color)) {
										$color_key = str_replace('bd_color_swatch_', '', $attribute_code);
										$color_swatches[$child_info['bd_color']][$color_key] = $color;
									}
								}

							## Add all of the other configurable attrbutes
							} else {
								if( array_key_exists($attribute_code, $child_info) && array_key_exists($attribute_code, $attribute_labels) ){
									$value = $child_info[$attribute_code];
									
									$combos[$child][$attribute_code] = $value;
									$combos_verbose[$child][] = $attribute_labels[$attribute_code]
										.':&nbsp;<em>'.$attribs[$attribute_code]['options_smarty'][$value].'</em>';
	
									if (!array_key_exists($attribute_code, $attributes)) {
										$attributes[$attribute_code] = array();
									}
									
									$attributes[$attribute_code][$value] = $attribs[$attribute_code]['options_smarty'][$value];
									
									## Add the child price to the price array
									## This only works right if there is only one configurable attribute
									$child_prices_by_label[ $value ] = $child_info['final_price'];
								}
							}
						}

						$combos_verbose[$child] = implode('; ', $combos_verbose[$child]);
					}
					
					$maps = array();
					$next_attribute_map = array();
					$num_attributes = count($attributes);
					
					## This array will go through the different valid attribute combinations
					foreach ($combos as $child => $combo) {
						$x = 1;
						foreach($combo as $attribute => $value) {
							if($x < $num_attributes) {
								$next_attribute_map[$attribute] = $attribute_codes[$x];
								$next_attribute = $combo[$attribute_codes[$x]];

								if (!array_key_exists($attribute, $maps)) {
									$maps[$attribute] = array();
								}
								if (!array_key_exists($value, $maps[$attribute])) {
									$maps[$attribute][$value] = array();
								}
								if (!in_array($next_attribute, $maps[$attribute][$value])) {
									$maps[$attribute][$value][] = $next_attribute;
								}
							}
							$x++;
						}
					}

					## This reformats (implodes) the array generated above
					foreach ($maps as $attribute => $values) {
						foreach ($values as $value => $mapped_values) {
							$maps[$attribute][$value] = implode(',', $mapped_values);
						}
					}

					## This build a unique attribute comination string for each child product
					$child_products = array();
					foreach ($combos as $child => $values) {
						$child_products[ $child ] = implode(',', $values);
					}
					
					$this->view->color_swatches = $color_swatches;
					$this->view->config_child_prices_by_label = $child_prices_by_label;
					$this->view->config_child_products = $child_products;
					$this->view->config_combos_verbose = $combos_verbose;
					$this->view->config_attributes = $attributes;
					$this->view->config_attribute_maps = $maps;
					$this->view->config_attribute_next = $next_attribute_map;
					$this->view->config_attribute_codes = implode(',', $attribute_codes);
					$this->view->config_attribute_labels = $attribute_labels;
				
				## Simple products
				} else {
					foreach ($group['attributes'] as $attrib) {
						if( $attrib['code']!='bd_color_swatch_one' && $attrib['code']!='bd_color_swatch_two' ){
							if (array_key_exists($attrib['code'], $product) && !empty($product[$attrib['code']])) {
								$configurables = array();
	
								if ($attribs[$attrib['code']]['type'] == 'select' || $attribs[$attrib['code']]['type'] == 'multiselect') {
									foreach ($attribs[$attrib['code']]['options'] as $option) {
										if ($option['value'] == $product[$attrib['code']]) {
											$configurables['value'] = $option['label'];
											break;
										}
									}
								} else {
									$configurables['value'] = $product[$attrib['code']];
								}
	
								$configurables['attribute_code'] = $attrib['code'];
								$configurables['attribute_id'] = $attrib['id'];
								$configurables['label'] = $attrib['label'];
								$product['configurables'][] = $configurables;
							}
						}
					}
				}
			}
		}
		
		$smarty_prices = Commerce_Common::getTemplatePrices( $prices );

		// for Integrated Dealer Referral
		$countries_table = new Countries();
		$this->view->countries = $countries_table->getCountriesArray("Select Country");
		$this->view->states = Cts_Common::getUsStatesArray("Select State");

		

		$idr_on_sale = false;
		$idr_price = null;
		
		if(array_key_exists('sale',$smarty_prices)){
			$idr_on_sale = $smarty_prices['sale'];
		}
		
		if(array_key_exists('price',$smarty_prices)){
			$idr_price = $smarty_prices['price'];
		}

		

		if(!$idr_on_sale){
			// get online dealers with this product
			$idr_products_table = new BlackdiamondIdrProducts();
			$idr_online_dealers = $idr_products_table->getDealerInfoByStylenum(substr($product['sku'], 0, 8), Cts_Registry::get('idr_dealers_to_show_on_pdp', 'blackdiamond'),$idr_price);
			$this->view->idr_dealers = $idr_online_dealers;
		}

		// RELATED PRODUCTS
		$tmp_relateds = $catalog_table->getRelatedProducts($product_id, $this->locale_code);
		$relateds = array();
		foreach ($tmp_relateds as $tmp_related) {
			$related = $tmp_related;
			$related['unserialized_media'] = unserialize($tmp_related['bd_media']);
			$relateds[] = $related;
		}
		$this->view->related_products = $relateds;

		// JOURNAL POSTS
		$blog_table = new BlogPosts();
		$users_table = new Users();
		$blogcats_table = new BlogCategories();
		
		$tmp_tags = array($activity['name'], $category['name'], $product['name'], $product['sku']);		
		$product_tags = explode(",",$product['bd_tags']);
		
		if(!is_array($product_tags)){
			$product_tags = array($product_tags);
		}		
		$tags = array();
		foreach($tmp_tags as $tag){
			$tag = trim($tag);
			if(substr($tag,0,2) != "BD"){
				$tag = strtolower($tag);	
			}
			if(!in_array($tag,$tags)){
				$tags[] = $tag;
			}
		}
		
		foreach($product_tags as $product_tag){
			$product_tag = trim($product_tag);
			if(!substr($product_tag,0,2) != "BD"){
				$product_tag = strtolower($product_tag);	
			}
			
			if(!in_array($product_tag,$tags)){
				$tags[] = $product_tag;
			}				
		}
		
		$tmp_journal_posts = $blog_table->fetchAllByTags($tags, false, 3);
		if (!is_null($tmp_journal_posts)) {
			$tmp_journal_posts = $tmp_journal_posts->toArray();
			$journal_posts = array();
			foreach ($tmp_journal_posts as $post) {
				$cats = $blogcats_table->getParsedSlugsByPostId($post['id'], true);
				$journal_posts[] = array(
					'cats' => $cats,
					'title' => $post['title'],
					'body' => strip_tags($post['body']),
					'publish_on' => $post['publish_on'],
					'slug' => $post['slug'],
					'author_fullname' => $users_table->getFullNameByUsername($post['author_username']),
					'thumbnail_url' => $blog_table->getThumbnailUrl($post['id'], 163),
				);
			}
		}
		$this->view->journal_posts = $journal_posts;

		// PRODUCT
		$this->view->product = $product;
		$this->view->prices = $smarty_prices;
		$this->view->prices_by_id = $prices_by_id;

		// ADVANCED PRODUCT DETAILS
		$this->view->product_details = $details;

		memory_profiler("end pdp");
	}

	/*
		Function: compare
	*/
	function compareAction() {
		$request = new Cts_Request($this->getRequest());
		$catalog = new CommerceMagentoCatalog();

		if ($request->has('cat_id') && $request->has('ids')) {
			$category_id = $request->cat_id;
			$product_ids = $request->ids;
		} elseif ($request->has('activity_key') && $request->has('category_key') && $request->has('product_ids')) {
			$activity_id = $catalog->getCategoryIdByUrlKey($request->activity_key, $this->locale_code);
			$category_id = $catalog->getCategoryIdByUrlKey($request->category_key, $this->locale_code);
			$product_ids = $request->product_ids;
		} else {
			$this->_redirect("/default/auth/missing");
		}

		$category = $catalog->getCategory($category_id, $this->locale_code);
		$this->view->category = $category;

		// FEATURE IMAGE
		$feature_photo = array();
		$feature_photo['location'] = NULL; // TODO - create this attribute in Magento
		$feature_photo['photographer_name'] = NULL; // TODO - create this attribute in Magento
		$feature_photo['featured_image_url'] = $category['blackdiamond_swiftcollective_cat_bg_full'];
		$feature_photo['featured_cropped_image_url'] = $category['blackdiamond_swiftcollective_cat_bg_cropped'];
		// blackdiamond_swiftcollective_cat_bg_caption
		$this->view->feature_photo = $feature_photo;

		if (is_null($activity_id)) {
			$activity = $catalog->getCategory($category['parent_id'], $this->locale_code);
		} else {
			$activity = $catalog->getCategory($activity_id, $this->locale_code);
		}
		$this->view->activity = $activity;

		$select_attributes = array();
		$select_attributes[] = 'name';
		$select_attributes[] = 'price';
		$select_attributes[] = 'description';
		$select_attributes[] = 'bd_media';

		$compare_attributes = array();
		$compare_attributes[] = 'price';
		$compare_attributes[] = 'description';

		$exclude_attributes = array();
		$exclude_attributes[] = 'short_description';

		$product_ids = explode(",", $product_ids);
		sort($product_ids);
		$prod_headers = array();
		foreach ($product_ids as $id) {
			$tmp_product = $catalog->getProduct($id, $this->locale_code);
			$prod_headers[] = array(

				'remove_url' => '/shop/'.$activity['url_key'].'/'.$category['url_key'].'/compare/'
					.trim(str_replace(','.$id.',', ',', ','.implode(',', $product_ids).','), ','),

				'pdp_url' => '/shop/'.$activity['url_key'].'/'.$category['url_key'].'/'.$tmp_product['url_key'],

			);
			if (isset($tmp_product['status']) && $tmp_product['status'] == '1') {
				foreach ($tmp_product['comparable_attributes'] as $attribute_key) {
					if (!in_array($attribute_key, $exclude_attributes)) {
						$select_attributes[] = $attribute_key;
						$compare_attributes[] = $attribute_key;
					}
				}
			}
		}
		$this->view->prod_headers = $prod_headers;
		$select_attributes[] = 'bd_features';
		$compare_attributes[] = 'bd_features';

		$comparison_data = array();

		foreach ($compare_attributes as $attribute_key) {
			$attribute = $catalog->getAttributeByCode($attribute_key);
			$comparison_data[$attribute_key] = array();
			$comparison_data[$attribute_key]['label'] = $attribute->_data['frontend_label'];
		}

		$filters = array();
		$filters['category_ids'] = array($category_id);
		$filters['__no_children'] = true;
		$filters['status'] = array('like'=>'1');

		$products = $catalog->getProducts($filters, $this->locale_code, $select_attributes);

		$thumbs = array();
		$other_product_options = array();
		$other_product_options[] = 'Select Another';

		foreach ($products as $product) {
			if (in_array($product['product_id'], $product_ids)) {
				$thumbs[$product['product_id']]['media'] = Commerce_Common::getThumbFromSerializedMedia($product['bd_media']);
				$thumbs[$product['product_id']]['name'] = $product['name'];
				$thumbs[$product['product_id']]['alt'] = $product['name'];
				foreach ($compare_attributes as $attribute_key) {
					if ($attribute_key == 'price') {
						// TODO - change this to pull from Magento already pre-formatted using Magento's formatPrice() method
						$comparison_data[$attribute_key][$product['product_id']] = '$'.sprintf('%.2f', $product[$attribute_key]);
					} else {
						$comparison_data[$attribute_key][$product['product_id']] = $product[$attribute_key];
					}
				}
			} else {
				// if it's not chosen for comparison, put it in the options for other products to select
				$other_product_options[$product['product_id']] = $product['name'];
			}
		}

		$this->view->comparison_data = $comparison_data;
		$this->view->thumbs = $thumbs;
		$this->view->other_product_options = $other_product_options;
	}

	/*
		Function: getBreadcrumb
	*/
	public function getBreadcrumb($category, $crumb = array()) {
		$crumb[] = $category;
		if ($category['level'] <= Cts_Registry::get('magento_root_category_level')) {
			$crumb_url = array();
			$crumbs = array_reverse($crumb);
			foreach ($crumbs as $x => $crumb) {
				$crumb_url[] = $crumb['url_key'];
				$crumbs[$x]['crumb_url'] = implode('/', $crumb_url).'/';
			}
			return $crumbs;
		} else {
			$catalog_table = new CommerceMagentoCatalog();
			$parent = $catalog_table->getCategory($category['parent_id']);
			return $this->getBreadcrumb($parent, $crumb);
		}
	}

	/*
		Function: sort_by_attribute_code
	*/
	public function sort_by_attribute_code($a, $b) {
		return ($a == 'bd_color') ? -1 : 1;
	}

}
